package com.dl.base.utils

import java.text.SimpleDateFormat
import java.util.*

//日期字符串转换Date实体
fun parseServerTime(serverTime: String, format: String = "yyyy-MM-dd HH:mm:ss"): Date? {

    val dateFormat = SimpleDateFormat(format, Locale.CHINESE)
    dateFormat.timeZone = TimeZone.getTimeZone("GMT+8:00")
    var date: Date? = null
    try {
        date = dateFormat.parse(serverTime)
    } catch (e: Exception) {
        e.printStackTrace()
    }

    return date
}

//秒数转换成时分秒
fun convertSecToTimeString(lSeconds: Long): String {
    val nHour = lSeconds / 3600
    var nMin = lSeconds % 3600
    val nSec = nMin % 60
    nMin /= 60
    return String.format("%02d小时%02d分钟%02d秒", nHour, nMin, nSec)
}

fun convertMilliToMinute(milli: Long): String {
    val minutes = milli / 1000 / 60
    val seconds = milli / 1000 % 60
    return String.format("%02d:%02d", minutes, seconds)
}

//Date对象获取时间字符串
fun getDateStr(date: Date, format: String = "yyyy-MM-dd HH:mm:ss"): String {
    val formatter = SimpleDateFormat(format)
    return formatter.format(date)
}

//时间戳转换日期格式字符串
fun timeStamp2Date(time: Long, format: String = "HH:mm:ss"): String {
    val sdf = SimpleDateFormat(format)
    return sdf.format(Date(time))
}

//日期格式字符串转换时间戳
fun date2TimeStamp(date: String, format: String): Long {
    try {
        val dateFormat = SimpleDateFormat(format)
        return (dateFormat.parse(date)!!.time / 1000)
    } catch (e: Exception) {
        e.printStackTrace()
    }

    return 0
}

//获取当前时间
fun dateNow(format: String = "yyyy-MM-dd HH:mm:ss"): String {
    val date = Date()
    val time = date.toLocaleString()
    val dateFormat = SimpleDateFormat(format)
    return dateFormat.format(date)
}

//时分秒转分
fun dateToMin(time: String): String {
    val s: String = time
    val index1 = s.indexOf(":")
    val index2 = s.indexOf(":", index1 + 1)
    val hh = s.substring(0, index1).toInt()
    val mi = s.substring(index1 + 1, index2).toInt()
    val ss = s.substring(index2 + 1).toInt()
    return (hh * 60 * 60).toString()

}

fun differentDaysByMillisecond(date1: Date?, date2: Date?): Int {
    return ((date2!!.getTime() - date1!!.getTime()) / (1000 * 3600 * 24)).toInt()
}

//截取日期显示时分 yyyy-MM-dd HH:mm:ss截取 HH:mm
fun dateToHourMin(date: String?): String {
    date?.let {
        val dateArr = date.split(" ")
        val time = dateArr[1]
        val endIndex = time.lastIndexOf(":")
        return time.substring(0, endIndex)
    }
    return ""
}
